import axios from "axios";
import apple from "../main"

const protocol = window.location.protocol;
const BASE_URL = `${protocol}//192.168.0.108:8081/lpdl`;//测试
// const BASE_URL = `${protocol}//www.lanpin123.com/talentwork`;//服务器地址

/**
 * 创建axios实例
 * @type {AxiosInstance}
 */
const service = axios.create({
  baseURL: BASE_URL,//api的base_url
  timeout: 50000//请求超时时间
});

/**
 * request拦截器==>对请求参数做处理
 */
service.interceptors.request.use(config => {
  config.method === 'post'
    ? config.data = {...config.data}
    : config.params = {...config.params};
  config.headers['Content-Type'] = 'application/json';
  return config;
}, error => {  //请求错误处理
  apple.$vux.toast.text(error, "middle");
  Promise.reject(error);
});

/**
 * response拦截器==>对响应做处理
 */
service.interceptors.response.use(
  response => {  //成功请求到数据
    apple.$vux.loading.hide();
    if (response.data.code === 0) {
      console.log(JSON.stringify(response.data))
      return response.data;
    } else {
      apple.$vux.toast.text(response.data.msg, "middle");//常规错误处理
      return response.data;
    }
  },
  error => {  //响应错误处理
    apple.$vux.toast.text('网络异常，请重试', "middle");
    apple.$vux.loading.hide();
    return Promise.reject(error)
  }
);

export default service;
